using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;

/// <summary>
/// 切图信息类，用于保存图片子图区域信息
/// </summary>
[Serializable]
public class ImageSliceInfo
{
    public bool isSliced;
    public float x;
    public float y;
    public float width;
    public float height;
}

/// <summary>
/// 公共工具类，封装了图片选择、子图选择及预览的逻辑
/// </summary>
public static class EditorImageSelector
{
    /// <summary>
    /// 绘制图片选择区域，支持从 SpriteSheet 中选择单个子图，并显示预览
    /// </summary>
    /// <param name="label">显示的标题</param>
    /// <param name="imagePath">图片路径（引用传递）</param>
    /// <param name="sliceInfo">切图信息（引用传递）</param>
    /// <param name="extraHandler">额外处理逻辑（可选）</param>
    public static void DrawImageSelection(string label, ref string imagePath, ref ImageSliceInfo sliceInfo, Action extraHandler = null,bool isSliced = true)
    {
        #if UNITY_EDITOR
        EditorGUILayout.BeginVertical();
        GUILayout.Label(label, EditorStyles.boldLabel);

        // 使用 ObjectField 让用户选择 Sprite 类型的图片
        Sprite selectedSprite = null;
        if (!string.IsNullOrEmpty(imagePath))
        {
            selectedSprite = AssetDatabase.LoadAssetAtPath<Sprite>(imagePath);
        }

        Sprite newSprite = (Sprite)EditorGUILayout.ObjectField( selectedSprite, typeof(Sprite), false,GUILayout.Height(60),GUILayout.Width(60));

        // Sprite newSprite = (Sprite)EditorGUILayout.ObjectField("选择图片", selectedSprite, typeof(Sprite), false);
        if (newSprite != selectedSprite)
        {
            if (newSprite != null)
            {
                imagePath = AssetDatabase.GetAssetPath(newSprite);

                // 加载该路径下所有子图
                Sprite[] sprites = AssetDatabase.LoadAllAssetsAtPath(imagePath).OfType<Sprite>().ToArray();
                if (sprites.Length > 1)
                {
                    List<string> spriteNames = new List<string>();
                    int currentIndex = 0;
                    for (int i = 0; i < sprites.Length; i++)
                    {
                        spriteNames.Add(sprites[i].name);
                        if (sprites[i] == newSprite)
                            currentIndex = i;
                    }
                    int selectedIndex = EditorGUILayout.Popup("选择切图", currentIndex, spriteNames.ToArray());
                    Sprite chosenSprite = sprites[selectedIndex];
                    if (sliceInfo == null)
                        sliceInfo = new ImageSliceInfo();
                    sliceInfo.isSliced = true;
                    sliceInfo.x = chosenSprite.rect.x;
                    sliceInfo.y = chosenSprite.rect.y;
                    sliceInfo.width = chosenSprite.rect.width;
                    sliceInfo.height = chosenSprite.rect.height;
                }
                else
                {
                    if (sliceInfo == null)
                        sliceInfo = new ImageSliceInfo();
                    sliceInfo.isSliced = false;
                    sliceInfo.x = 0;
                    sliceInfo.y = 0;
                    sliceInfo.width = 0;
                    sliceInfo.height = 0;
                }
            }
            else
            {
                imagePath = "";
                sliceInfo = null;
            }
        }

        if (isSliced)
        {
            // 预览部分：如果有 imagePath 则显示预览
            if (!string.IsNullOrEmpty(imagePath))
            {
                if (sliceInfo != null && sliceInfo.isSliced)
                {
                    Sprite sprite = AssetDatabase.LoadAssetAtPath<Sprite>(imagePath);
                    if (sprite != null && sprite.texture != null)
                    {
                        Texture2D tex = sprite.texture;
                        // 根据 sliceInfo 计算子图在贴图中的归一化区域
                        Rect r = new Rect(sliceInfo.x, sliceInfo.y, sliceInfo.width, sliceInfo.height);
                        Rect texCoords = new Rect(r.x / tex.width, r.y / tex.height, r.width / tex.width, r.height / tex.height);
                        float maxPreviewHeight = 100f;
                        float previewWidth = 100f;
                        Rect previewRect = GUILayoutUtility.GetRect(previewWidth, maxPreviewHeight);
                        GUI.DrawTextureWithTexCoords(previewRect, tex, texCoords);
                    }
                }
                else
                {
                    Texture2D tex = AssetDatabase.LoadAssetAtPath<Texture2D>(imagePath);
                    if (tex != null)
                    {
                        float aspect = (float)tex.width / tex.height;
                        float maxPreviewHeight = 75;
                        float previewWidth = maxPreviewHeight * aspect;
                        Rect previewRect = GUILayoutUtility.GetRect(previewWidth, maxPreviewHeight);
                        EditorGUI.DrawPreviewTexture(previewRect, tex, null, ScaleMode.ScaleToFit);
                    }
                }
            }
        }
        

        // EditorGUILayout.Space();
        // EditorGUILayout.LabelField("", GUI.skin.horizontalSlider);
        // EditorGUILayout.Space();
        EditorGUILayout.EndVertical();
        extraHandler?.Invoke();
        #endif
    }
}